<template>
  <div>
    <customContainer ref="customContainerRef" :config="config" />
    <confirm-dialog ref='confirmDialogRef' @success="success"/>
  </div>
</template>

<script setup lang="ts" name="AirSeaExpressIndex">
import { ref, getCurrentInstance, computed, reactive, defineAsyncComponent } from 'vue'
import { ElButton, ElMessageBox, ElMessage, ElDivider } from 'element-plus'
import { useRouter } from 'vue-router'
import { DictDirection } from '@/store/modules/dicts'
import { depClone } from '@/utils'
import { 
  getSeaAirSendFinanceAccountlist, 
  dispatchWriteOffSend, 
  confirmTheBill, 
  confirmPushBill, 
  queryAccountDetails, 
  dispatchCancelWriteOffSend 
} from '@/api/finance/receiverManange'
import { tableItem, indexObject } from '../receiveabeTypes'


const ConfirmDialog  = defineAsyncComponent(() => import("./components/ConfirmDialog.vue"))
const confirmDialogRef = ref()

const router = useRouter()
const customContainerRef = ref()

const multipleSelection = ref<tableItem[]>([])
const {
  appContext: {
    config: {
      globalProperties: { $download },
    },
  },
} = getCurrentInstance()

const success = () => {
    customContainerRef.value.getList()
}

const queryParams = reactive<indexObject>({
  pageSize: 10,
  pageNum: 1,
  customerName: undefined,
  serialNo: undefined,
  businessManager: undefined,
  endTime: undefined,
  beginTime: undefined,
  timeRange: undefined,
  status: undefined,
  transportType: undefined,
})

const operationFn = (msg, fn, ...rest) => {
      ElMessageBox.confirm(msg, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(() => {   
        fn(...rest).then(res => {
          if (res.code === 200) {
            ElMessage.success('操作成功！')
            customContainerRef.value.getList()
          }
        })
      })
}

const exportLoading = ref<boolean>(false)
const exportOrderLoading = ref<boolean>(false)
const config = computed({
  get() {
    return {
      query: {
        fields: [
          {
            // type: 'select',
            label: '客户名称',
            prop: 'customerCode',
            option: {
              clearable:true,
              // dictInfo: { dict: DictDirection.客户 },
            },
          },
          {
            label: '账单编号',
            prop: 'serialNo',
          },
          {
            type: 'select',
            label: '业务员',
            prop: 'businessManager',
            option: {
              clearable:true,
              dictInfo: { dict: DictDirection.员工信息 },
            },
          },
          {
            type: 'date-picker',
            label: '账单时间',
            prop: 'timeRange',
            option: {
              startPlaceholder: "开始时间",
              endPlaceholder: "结束时间",
              type: 'daterange',
            },
          },
          {
            type: 'select',
            label: '所属站点',
            prop: 'site',
            option: {
              clearable:true,
              dictInfo: { dict: DictDirection.收货站点 },
            },
          },
          {
            type: 'select',
            label: '账单状态',
            prop: 'status',
            option: {
              clearable:true,
              dictInfo: { dict: DictDirection.账单状态 },
              multiple:true
            },
          },
          // {
          //   type: 'select',
          //   label: '渠道',
          //   prop: 'transportType',
          //   option: {
          //     dictInfo: { dict: DictDirection.运输类型 },
          //   },
          // },
        ],
        queryParams,
        formOption: {
          labelWidth: '150px'
        },
      },
      btns: [
        {
          title: '导出账单',
          type: 'primary',
          loading: exportLoading.value,
          onClick: (e) => {
            exportLoading.value = true
            const data = queryParams
            $download(
              'finance/seaAirSendFinanceAccount/listExport', 
              data, 
              `空海派、快递账单_${ new Date().getTime() }.xlsx`,
            ).finally(() => {
              exportLoading.value = false
            })
          },
        },
        {
          title: '导出账单及订单',
          type: 'danger',
          loading: exportOrderLoading.value,
          onClick(e) {
            const data:indexObject = {}
            if (multipleSelection.value.length) {
              data.serialNo = multipleSelection.value.map(i => i.serialNo).join(',')
            }
            exportOrderLoading.value = true
            $download(
              'finance/seaAirSendFinanceAccount/listDetailsExport', 
              data, 
              `空海派、快递账单详情_${ new Date().getTime() }.xlsx`,
            ).finally(() => {
              exportOrderLoading.value = false
            })
          },
        },
      ],
      table: {
        columns: [
          { type: 'selection', width: '55' },
          { label: '账单时间', align: 'center', prop: 'endDate' },
          { label: '账单编号', align: 'center', prop: 'serialNo' },
          { label: '客户名称', align: 'center', prop: 'customerName' },
          { label: '应收总金额', align: 'center', prop: 'amount' },
          { label: '总票数', align: 'center', prop: 'totalVotes' },
          { label: '总件数', align: 'center', prop: 'totalPiece' },
          { label: '总实重', align: 'center', prop: 'totalWeight' },
          { label: '总材积重', align: 'center', prop: 'totalVolumeWeight' },
          { label: '总计费重', align: 'center', prop: 'totalChargeWeight' },
          { label: '业务员',  align: 'center',  prop: 'businessManager' },
          { label: '所属站点',
            align: 'center',
            prop: 'site',
            autoFormatter: {
              dict: DictDirection.收货站点,
              rowKey: 'site',
            },
          },
          { label: '账单状态',
            align: 'center',
            prop: 'status',
            autoFormatter: {
              dict: DictDirection.账单状态,
              rowKey: 'status',
            },
          },
          { label: '已收款金额', align: 'center', prop: 'paidAmount' },
          { label: '未收款金额', align: 'center', prop: 'uncollectedAmount' },
          { label: '渠道',
            align: 'center',
            prop: 'transportType',
            autoFormatter: {
              dict: DictDirection.运输类型,
              rowKey: 'transportType',
            } },
          {
            label: '操作',
            align: 'center',
            width: '300',
            fixed: 'right',
            render(h, { row }) {
              return [
                h(
                  ElButton,
                  {
                    text: true,
                    type: 'primary',
                    onClick: () => {
                      router.push({
                        name: 'AirSeaExpressDetail',
                        params: {
                          serialNo: row.serialNo,
                        },
                        query:{
                           amount: row.amount,
                           paidAmount: row.paidAmount,
                           uncollectedAmount: row.uncollectedAmount,
                        }
                      })
                    },
                  },
                  {
                    default: () => '账单详情',
                  },
                ),
                h(
                  ElDivider,
                  {
                    direction:'vertical'
                  }
                ),
                h(
                  ElButton,
                  {
                    text: true,
                    type: 'primary',
                    disabled: row.status !== 1,
                    onClick: () => {
                      operationFn(
                        '是否推送？', 
                        confirmPushBill,
                        row.id,
                        row.serialNo,
                        )
                    },
                  },
                  {
                    default: () => '推送',
                  },
                ),
                h(
                  ElDivider,
                  {
                    direction:'vertical'
                  }
                ),
                h(
                  ElButton,
                  {
                    text: true,
                    disabled: row.status !== 2,
                    type: 'primary',
                    onClick:async () => {
                      confirmDialogRef.value.open(row.serialNo)     
                    },
                  },
                  {
                    default: () => '确认',
                  },
                ),
                h(
                  ElDivider,
                  {
                    direction:'vertical'
                  }
                ),
                h(
                  ElButton,
                  {
                    text: true,
                    disabled: row.status !== 3,
                    type: 'primary',
                    onClick: () => {
                      operationFn(
                        '此操作将核销此账单全部金额, 是否确定？', 
                        dispatchWriteOffSend,
                        {
                          serialNo: row.serialNo,
                          amount: row.amount,
                          paidAmount: row.paidAmount,
                        })
                    },
                  },
                  {
                    default: () => '核销',
                  },
                ),
                h(
                  ElDivider,
                  {
                    direction:'vertical'
                  }
                ),
                h(
                  ElButton,
                  {
                    text: true,
                    type: 'primary',
                    disabled: row.status !== 4,
                    onClick: () => {
                      operationFn(
                        '是否反审核？', 
                        dispatchCancelWriteOffSend,
                        {
                          serialNo: row.serialNo,
                          amount: row.amount,
                          paidAmount: row.paidAmount,
                        })
                    },
                  },
                  {
                    default: () => '反审核',
                  },
                ),
              ]
            },
          },
        ],
        event: {
          onSelectionChange: (rows) => {
            multipleSelection.value = rows
          },
        },
      },
      api: (data) => {
        const params = depClone(data)
        params.beginTime = undefined
        params.endTime = undefined
        
        if(params.serialNo)
          params.serialNo = params.serialNo.replaceAll(/\s+/g, ',')
          
        if(!params.serialNo)
          delete params.serialNo

        if(params.status && Array.isArray(params.status) )
          params.status = params.status.join(',')

        if(!params.status)
          delete params.status

        if(params.timeRange && Array.isArray(params.timeRange) ){
          params.beginTime = params.timeRange[0]
          params.endTime = params.timeRange[1]
          delete params.timeRange
        }

        return getSeaAirSendFinanceAccountlist(params)
      },
    }
  },
  set(val) {
    return val
  },
})

</script>